package com.mssh.login.core;

import com.mssh.entity.exception.BusinessException;
import com.mssh.entity.pojo.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2025/03/25/14:43
 * @Description:
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        return new Result().failed(e.getCode(), e.getMsg());
    }

    /**
     * 处理参数校验异常（@Valid 触发的异常）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return new Result().failed(400, message);
    }

    /**
     * 处理其他未捕获异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleGlobalException(Exception e) {
        e.printStackTrace();  // TODO:生产环境应记录日志
        return new Result().failed(500, "系统繁忙，请稍后再试");
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AuthorizationException.class)
    public Result<?> handleAuthorizationException() {
        return new Result().failed(403, "没有访问权限");
    }

    /**
     * 处理认证失败异常
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result<?> handleAuthenticationException(AuthenticationException e) {
        return new Result().failed(401, e.getMessage());
    }
}
